<?php

namespace app\common;

class Common
{

    /**
     * 获取随机数
     *
     * @param int $num
     * @return string
     */
    public static function getRand($num = 7): string
    {
        $words = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $max = strlen($words) - 1;
        $str = '';
        for ($i = 0; $i < $num; $i++) {
            $str .= $words[rand(0, $max)];
        }

        return $str;
    }

    /**
     * 获取请求参数
     *
     * @return array
     */
    public static function getRequestParams(): array
    {
        $request = \Yii::$app->request;

        $requestParams = [];
        $get = $request->get();

        $requestParams = $get ? array_merge($requestParams, $get) : $requestParams;

        $body = $request->getRawBody() ? json_decode($request->getRawBody(), true) : [];
        $requestParams = $body ? array_merge($requestParams, $body) : $requestParams;

        $post = $request->post();
        $requestParams = $post ? array_merge($requestParams, $post) : $requestParams;

        return self::trimRequestParams($requestParams);
    }

    /**
     * 递归处理
     *
     * @param array $params
     * @return array
     */
    public static function trimRequestParams(array $params): array
    {
        foreach ($params as $key => $item) {
            if (is_array($item)) {
                $params[$key] = self::trimRequestParams($item);
            } else {
                $params[$key] = is_string($item) ? trim($item) : $item;
            }
        }

        return $params;
    }

}